﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text.RegularExpressions;
using Newtonsoft.Json;
using System.Linq;

namespace DeploymentCopy.Model
{
    public class DataService : IDataService
    {
        private DBEntities _db = new DBEntities();

        public void GetData(Action<ZipLog, Exception> callback)
        {
            // Use this to connect to the actual data service

            //var item = new DataItem("Welcome to MVVM Light");
            callback(null, null);
        }

        public void GetZipLogData(Config config, Action<List<ZipLog>, Exception> callback)
        {
            //List<ZipLog> listZipLogs
            try
            {
                /*using (StreamReader sr = new StreamReader("ZipLogs.json"))
                {
                    List<ZipLog> listZipLogs = JsonConvert.DeserializeObject<List<ZipLog>>(sr.ReadToEnd());
                    callback(listZipLogs, null);
                }*/
                string format = config.DateFormat;
                CultureInfo provider = new CultureInfo(config.CulturalName);
                DateTime minDate = DateTime.ParseExact(config.StartDateFilter, format, provider);

                var listZipLogs = _db.ZipLogs.Where(n => n.DateName >= minDate).ToList();
                foreach (var item in listZipLogs)
                {
                    item.IsDeployedStaging = item.WasDeployedStaging;
                    item.IsDeployedProduct = item.WasDeployedProduct;
                }
                
                var listFiles =
                    GetFiles(config)
                    .Where(n => DateTime.ParseExact(Path.GetFileNameWithoutExtension(n), format, provider) >= minDate);
                string[] addedFiles ;
                if (listZipLogs.Count > 0)
                    addedFiles = listFiles.Select(n => Path.GetFileName(n)).Except(listZipLogs.Select(n => n.FileName)).ToArray();
                else
                    addedFiles = listFiles.Select(n => Path.GetFileName(n)).ToArray();

                ZipLog zl;
                if (addedFiles.Length > 0)
                {
                    string tmp = "";
                    foreach (var file in addedFiles)
                    {
                        zl = new ZipLog()
                                 {
                                     FileName = file,
                                     //Folder = new DirectoryInfo(Path.GetDirectoryName(listFiles.First(n => n.Contains(file)))).Name,
                                     DateName = DateTime.ParseExact(Path.GetFileNameWithoutExtension(file), format, provider),
                                     //Size = (new FileInfo(file)).Length,
                                     WasDeployedStaging = false,
                                     WasDeployedProduct = false,
                                     IsDeployedStaging = false,
                                     IsDeployedProduct = false,
                                     IgnoredStaging = false,
                                     IgnoredProduct = false
                                 };
                        //zl.Iteration = Convert.ToInt32(zl.Folder.Split('-')[1]);
                        tmp = listFiles.First(n => n.Contains(file));
                        zl.Folder = new DirectoryInfo(Path.GetDirectoryName(tmp)).Name;
                        zl.Size = (new FileInfo(tmp)).Length;
                        listZipLogs.Add(zl);
                        _db.ZipLogs.AddObject(zl);
                    }
                    _db.SaveChanges();
                }

                callback(listZipLogs.Where(n => !n.WasDeployedProduct || !n.WasDeployedStaging).OrderBy(n => n.DateName).ToList(), null);
            }
            catch (Exception ex)
            {
                callback(null, ex);
            }
        }

        public void SaveZipLogData()
        {
            _db.SaveChanges();
        }

        public List<string> GetFiles(Config config)
        {
            string[] directoryPaths = Directory.GetDirectories(config.LookupDirectory, config.DirectoryPattern);
            string[] files;
            Regex regex = new Regex(config.RegularSearchPattern);
            List<string> listFiles = new List<string>();
            foreach (var directoryPath in directoryPaths)
            {
                files = Directory.GetFiles(directoryPath, "*.zip");
                foreach (var file in files)
                {
                    if (regex.IsMatch(Path.GetFileName(file)))
                        listFiles.Add(file);
                }
            }
            return listFiles;
        }

        public Config LoadConfig()
        {
            using (StreamReader sr = new StreamReader("config.json"))
            {
                Config config = JsonConvert.DeserializeObject<Config>(sr.ReadToEnd());
                return config;
            }
        }

        public void SaveConfig(Config config)
        {
            using (StreamWriter sw = new StreamWriter("config.json", false))
            {
                sw.Write(JsonConvert.SerializeObject(config));
            }
        }
    }
}